import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { ScrollView, Button, Map, Swiper, SwiperItem, Picker, Input, Image } from '@tarojs/components'
import Request from "../../api";
import Event from "../../event";
import {debounce} from '../../utils';

export default class Index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      repairEvents: [],
      list: [],
      content: '',
      page: 1,
      pageSize: 20,
      activeTab: 'VILLAGE',
      currentUserId: ''
    };
    this.loadEvents = this.loadEvents.bind(this);
    this.handleSearch = this.handleSearch.bind(this);
    this.handleTabChange = this.handleTabChange.bind(this);
    this.loadingMore = false;
    this.canLoadMore = true;
    Event.on('updateRepairEvent', async () => {
      this.loadingMore = false;
      this.canLoadMore = true;
      this.loadEvents();
    });
    this.stateMap = {
      '0': {
        color: '#f1a63f',
        label: '待处理'
      },
      '1': {
        color: '#479bfe',
        label: '处理中'
      },
      '2': {
        color: 'green',
        label: '处理完成'
      }
    }
  }

  componentWillMount () {
    this.loadEvents();
  }

  componentWillUnmount () {}

  componentDidHide () { }


  async loadEvents() {
    if (this.loadingMore || !this.canLoadMore) {
      return;
    }
    await Taro.showLoading();
    this.loadingMore = true;
    try {
      let res = await Request.get(`/business/repair_events/list?content=${this.state.content}&userId=${this.state.currentUserId}&pageNum=${this.state.page}&pageSize=${this.state.pageSize}`);
      if (res.data.code !== 200) {
        throw new Error();
      }
      let temp = [];
      if (this.state.page > 1) {
        temp = this.state.list;
      }
      this.setState({
        list: temp.concat(res.data.rows)
      }, () => {
        if (this.state.list.length === res.data.total) {
          this.canLoadMore = false;
        }
        this.loadingMore = false;
      })
    } catch (e) {
      console.log('加载报修数据失败')
    } finally {
      await Taro.hideLoading();
    }
  }

  async handleSearch(value) {
    this.canLoadMore = true;
    this.setState({
      content: value
    })
    this.setState({
      page: 1,
      pageSize: 20
    }, this.loadEvents)
    // debounce(() => {
    //
    // }, 100)
  }

  async handleScrollToEnd() {
    this.setState({
      page: ++this.state.page,
      pageSize: 20
    }, this.loadEvents)
  }

  async handleTabChange(activeIndex) {
    this.canLoadMore = true;
    this.loadingMore = false;
    this.setState({
      activeTab: activeIndex,
      page: 1,
      pageSize: 20,
      currentUserId: activeIndex === 'MINE' ? global.userInfo.userId : ''
    }, this.loadEvents)
  }

  render () {

    let  {list, jobName, activeTab} = this.state;
    return (
      <View>
        <View className='tab_container'>
          <Text className={activeTab === 'VILLAGE' ? 'tab_btn_item tab_btn_item_active' : 'tab_btn_item'} onClick={() => this.handleTabChange('VILLAGE')}>小区报修概览</Text>
          <Text className={activeTab === 'MINE' ? 'tab_btn_item tab_btn_item_active' : 'tab_btn_item'} onClick={() => this.handleTabChange('MINE')}>我的报修</Text>
        </View>
        <View className='repair_event_list'>
          <View className='action_header'>
            <View className='search_input'>
              <Text className='iconfont icon-sousuo color-grey size36'/>
              <Input type='text' value={jobName} onInput={(e) => this.handleSearch(e.detail.value)} placeholder='搜索内容'/>
            </View>
            <Text className='repair_report' onClick={() => {
              global.isEventDetail = false;
              Taro.navigateTo({
                url: '/pages/repair_report/index'
              })
            }}>我要报修</Text>
          </View>

          <ScrollView  scrollY={true} style={{height: 'calc(100vh - 60px)'}} onScrollToLower={this.handleScrollToEnd.bind(this)}>
            {
              list.length !== 0 ? list.map(item => {
                  return (
                    <View className='repair_event_item'>
                      <View className='row'>
                        <Text className='job_name'>{item.villageName} {item.name}</Text>
                        <Text className='job_salary'>{item.createTime}</Text>
                      </View>
                      <View className='row'>
                        <Text className='job_content'>{item.content}</Text>
                        <Text className='job_status' style={{color: this.stateMap[item.status].color}}>{this.stateMap[item.status].label}</Text>
                      </View>
                      <View className='row'>
                        <Text className='job_address'>{item.villageName} {item.address}</Text>

                        <View className='master_info'>

                        </View>
                        <View className='action_container'>
                          <Text className='size32 color-green apply' onClick={async () => {
                            global.currentRepairEvent = item;
                            global.isEventDetail = true;
                            await Taro.navigateTo({
                              url: '/pages/repair_report/index'
                            })
                          }}>查看详情</Text>
                        </View>
                      </View>

                    </View>
                  );
                })
                :
                <View className='message_container'>
                  尚未有相关报修信息
                </View>
            }
          </ScrollView>
        </View>

      </View>
    )
  }
}
